﻿using ERPSystem.Common.Domains.CustomerProfileCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace SalesManagementCommon.API.SalesManagementCommons.SalesManagementSerach
{
    public class CustomerProfileSearchHander : IRequestHandler<CustomerProfileSearchCommand, ResultPage<CustomerProfile>>
    {
        private IBaseRepository<CustomerProfile> _customerProfileRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="customerProfileRepository"></param>
        public CustomerProfileSearchHander(IBaseRepository<CustomerProfile> customerProfileRepository)
        {
            _customerProfileRepository = customerProfileRepository;
        }

        /// <summary>
        /// 客户信息搜索
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<CustomerProfile>> Handle(CustomerProfileSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<CustomerProfile>() { Code = (int)CommonErrorCode.Search, TotalCount = 0, PageCount = 0 };
            try
            {
                var seedweanings = await (await _customerProfileRepository.GetAll()).ToListAsync();
                if (!string.IsNullOrEmpty(request.BusinessContacts)) //联系人
                {
                    seedweanings = seedweanings.Where(p => p.BusinessContacts == request.BusinessContacts).ToList();
                }
                if (!string.IsNullOrEmpty(request.CustomerName))//客户名称
                {
                    seedweanings = seedweanings.Where(p => p.CustomerName.Contains(request.CustomerName)).ToList();
                }

                result.TotalCount = seedweanings.Count;
                result.PageCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                seedweanings = seedweanings.OrderByDescending(c => c.CustomerProfileId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = seedweanings;
            }
            catch (Exception ex)
            {
                throw;
            }
            return result;
        }
    }
}
